import asyncio
import http.cookies
from datetime import datetime

import aiohttp

from core import blivedm
from config import SESSDATA, ROOM_ID, SHOW
from logger import logger


class Handler(blivedm.BaseHandler):
    def __init__(self, queue: asyncio.Queue):
        self.queue = queue
        self.records = {i: 0 for i in SHOW.values()}
        self.shows = SHOW.keys()
        self.current = datetime.now()

    def handle(self, client: blivedm.BLiveClient, command: dict):
        if self.queue.full():
            return

        cmd = command["cmd"]

        if cmd in self.shows:
            self.records[SHOW[cmd]] += 1

        asyncio.create_task(self.queue.put(command))

        if (datetime.now() - self.current).seconds > 60:
            logger.info(" ".join(map(lambda i: f" {i[0]}:{i[1]:<3}", self.records.items())))
            self.current = datetime.now()
            self.records = {i: 0 for i in self.records.keys()}


def init_session():
    cookies = http.cookies.SimpleCookie()
    cookies["SESSDATA"] = SESSDATA
    cookies["SESSDATA"]["domain"] = "bilibili.com"
    session = aiohttp.ClientSession()
    session.cookie_jar.update_cookies(cookies)

    return session


async def bilibili(queue: asyncio.Queue):
    logger.info(f"监听直播间中，{ROOM_ID=}")

    client = blivedm.BLiveClient(ROOM_ID, session=init_session())
    handler = Handler(queue)
    client.set_handler(handler)

    try:
        client.start()
        await client.join()
    finally:
        await client.stop_and_close()
        logger.error(f"EXIT")
